﻿using chihuopig.IService;
using chihuopig.Model;
using chihuopig.Tool;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using chihuopig.DTO;

namespace chihuopig.Service
{
    public class AdminService : DBService, IAdminService
    {
        
        public Task<long> Insertable(Admin Model)
        {
            return Sqlclient.Insertable(Model).ExecuteReturnBigIdentityAsync();
            
        }

        public  Task<int> Deleteable(long Id)
        {
            return  Sqlclient
                        .Updateable<Admin>()
                        .UpdateColumns(it=>new Admin() {IsDelete=true })
                        .Where(c => c.Id == Id)
                        .ExecuteCommandAsync();
        }

        public  Task<int> Updateable(Admin Model)
        {
            return  Sqlclient.Updateable(Model).ExecuteCommandAsync();
        }

        public Task<List<Admin>> GetPage(int pageIndex=1, int PageSize =10)
        {
            return Sqlclient.Queryable<Admin>().Where(c=>c.IsDelete==false).OrderBy(s => s.Addtime, SqlSugar.OrderByType.Desc).ToPageListAsync(pageIndex, PageSize);
        }

        public Admin ChenkAdminLogin(string adminName, string Pwdword)
        {

            Admin admin= Sqlclient.Queryable<Admin>().Where(s => s.Name == adminName&&s.IsDelete == false).Single();
            if (admin!=null)
            {
                return  UtilityHelper.GetMd5(Pwdword, admin.salt) == admin.password ? admin : null;
            }

            return admin;
        }

        public Task<Admin> ChenkAdminLoginAsync(string adminName, string Pwdword)
        {
            var b= new Task<Admin>(() => { return ChenkAdminLogin(adminName, Pwdword); });
            b.Start();
            return b;
        }

        public Task<double> GetPageTotal(int PageSize)
        {
            return Task.Factory.StartNew<double>(a =>
            {
                double size=Convert.ToDouble(a);
                double bnum = Sqlclient.Queryable<Admin>().Where(c => c.IsDelete == false).OrderBy(s => s.Addtime, SqlSugar.OrderByType.Desc).Count() / size;
                //Math.Ceiling(bnum);
                return Math.Ceiling(bnum);

            }, PageSize);
        }

        public Task<Admin> EditAsync(long Id)
        {
           return Sqlclient.Queryable<Admin>().Where(s => s.Id == Id).FirstAsync();
        }

        public Task<int> delAll(long[] Id)
        {
           return Task.Factory.StartNew<int>(s=> {
               string ls = string.Join(",", (long[])s);
               string sql = $"update  Admin set IsDelete='1' where id in ({ls})";
               return 
               Sqlclient.Ado.ExecuteCommand(sql);
              
            }, Id);
           
        }

        public int AdminRole(long AdminId, long[] Role)
        {
            StringBuilder sb = new StringBuilder();
            List<SqlSugar.SugarParameter> parlist = new List<SqlSugar.SugarParameter>();
            foreach (var item in Role)
            {
                sb.Append(" insert into AdminRole(AdminId,RoleId,Addtime) values(@AdminId,@RoleId,now()); ");
                parlist.Add(new SqlSugar.SugarParameter("@AdminId", AdminId));
                parlist.Add(new SqlSugar.SugarParameter("@RoleId", item));
            }

           return Sqlclient.Ado.ExecuteCommand(sb.ToString(), parlist);
        }

        public Task<int> AdminRoleEdit(AdminRoleEditDTO model)
        {
           return Task.Factory.StartNew(s =>
            {
                AdminRoleEditDTO mo = (AdminRoleEditDTO)s;
                Admin adminMo= Sqlclient.Queryable<Admin>().Where(a => a.Id == mo.AdminId).Single();
                try
                {
                    Sqlclient.Ado.BeginTran();
                    StringBuilder sql = new StringBuilder();
                    Sqlclient.Ado.ExecuteCommand($"update Admin set password='{UtilityHelper.GetMd5(mo.pass, adminMo.salt)}' where id='{mo.AdminId}' ");
                    Sqlclient.Ado.ExecuteCommand($"delete from AdminRole where RoleId not in ({string.Join(",", mo.RoleId)}) and AdminId='{mo.AdminId}'" );
                    foreach (var item in mo.RoleId)
                    {
                        if (Sqlclient.Queryable<AdminRole>().Where(a => a.AdminId == mo.AdminId&&a.RoleId==item).Single()==null)
                        {
                            Sqlclient.Ado.ExecuteCommand($"insert into AdminRole(AdminId,RoleId,Addtime) values ('{mo.AdminId}','{item}',now()) ");

                        }
                    }
                
                    Sqlclient.Ado.CommitTran();
                    return 1;
                }
                catch(Exception ex)
                {
                    Sqlclient.Ado.RollbackTran();
                    return 0;
                }
                //string sql = $"update Admin set password='{UtilityHelper.GetMd5(mo.pass, adminMo.salt)}' where id='{mo.AdminId}' ";
                
            }, model);
        }
    }
}
